<template>
  <div class="app-container">
    <!-- 搜索和 操作的行为区 -->
    <div class="conduct">
      <el-input v-model="listQuery.keyword" placeholder="角色名称" class="conduct-input">
        <el-button slot="append" icon="el-icon-search" @click="handleFilter" />
      </el-input>
      <el-button class="danger-btn" @click="handleUpdate(-1, 'create')">创建</el-button>
      <el-button class="primary-btn" @click="handleDelmultip">删除</el-button>
    </div>
    <!-- tabs 切换不同角色 -->
    <div class="tab-container">
      <el-tabs v-model="active_name" type="card" @tab-click="handleClickTab">

        <el-tab-pane v-for="item in list_role" :key="item.roleId" :name="item.roleId" :data-roleid="item.roleId">
          <span slot="label"><i class="iconfont icon-fangkuangweixuan" /> {{ item.roleName }}</span>
          <div class="role-tilte">
            <div class="title-item"> <div class="title-icon" /> 角色ID: {{ item.roleName }}</div>
            <div class="title-item"> <div class="title-icon" /> 创建时间: {{ item.createTime }}</div>
            <div class="title-item"> <div class="title-icon" /> 备注: {{ item.remark }}</div>
          </div>
          <div class="role-tree">
            <div class="tree-title"> <div class="title-icon" /> 角色权限 </div>
            <div class="tree-container">
              <el-tree
                :data="item.menu_perm"
                show-checkbox
                node-key="menuId"
                :default-expanded-keys="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
                :default-checked-keys="item.check_perm"
                :props="defaultProps"
                @check="updateData"
              />
            </div>

          </div>
        </el-tab-pane>

      </el-tabs>
    </div>

    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="changePage()"
    />

    <el-dialog title="创建角色" :visible.sync="dialogFormVisible" width="40%" center :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model="temp.roleName" type="text" maxlength="18" placeholder="请输入账户名" />
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="temp.remark" />
        </el-form-item>
        <el-form-item label="配置权限:" required>
          <el-tree
            ref="tree_add"
            :data="login_menu"
            show-checkbox
            node-key="menuId"
            :default-expanded-keys="[1, 2, 3, 4]"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="danger-btn" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button class="primary-btn" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="提示" width="30%" center :close-on-click-modal="false">
      <div class="del-data del-img"><img :src="require('../../assets/img/del.png')" alt=""></div>
      <div class="del-data del-notify">确定对账号进行【删除】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="danger-btn" @click="dialogPvVisible = false">取消</el-button>
        <el-button class="primary-btn" @click="delData">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils' // 解析时间
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { delRole, addRole, editRole, listRole, permRole } from '@/api/system'
import { menuList } from '@/api/login'
import { validPass, validRoleName } from '@/utils/validate'
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'Role',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!validPass(value)) {
        callback(new Error('8~16位,包含大小写字母和数字, 可以有特殊字符'))
      } else { callback() }
    }
    const validateRolename = (rule, value, callback) => {
      // if(!value || (value && (value.length < 2 || value.length > 16))) {
      if (!validRoleName(value)) {
        callback(new Error('4~16位,字母和数字组合'))
      } else { callback() }
    }

    return {
      multipleSelection: [1],
      is_multip: false, // 是否批量删除
      tableKey: 0,
      list: null,
      total: 0, // 总条数
      listLoading: true,
      listQuery: {
        page: 1, // 第几页
        limit: 10, // 每页显示的条数row
        keyword: '' // 搜索关键字
      },
      calendarTypeOptions,
      temp: {
        roleId: '',
        roleName: '',
        remark: '',
        permIds: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      del_id: '',
      del_index: null,
      dialogPvVisible: false,
      rules: {
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        roleName: [{ required: true, trigger: 'blur', validator: validateRolename }]
      },
      list_role: [], // 获取角色名和角色id的 列表
      active_name: '', // 当前活跃的角色
      login_userId: '', // 当前登录者的  userId
      login_menu: '', // 当前登录者的 权限菜单
      defaultProps: { // tree 配置项
        children: 'childrenList',
        label: 'name'
      }
    }
  },
  created() {
    // 1 网络请求: 获取当前登录者的 权限菜单
    new Promise((resolve, reject) => {
      menuList().then(res => {
        // this.login_menu = res.data || JSON.parse(window.localStorage.getItem('munulist')) || this.$store.getters.menulist || []
        this.login_menu = res.data || []
        resolve()
      })
    }).then(res => {
      this.getListRole() // 获得角色列表
    })
    // 2 本地获取: 获取当前登录者的 权限菜单
    // this.login_menu = JSON.parse(window.localStorage.getItem('munulist')) || []
    // 3 vuex获取 this.login_menu = this.$store.getters.menulist
  },
  mounted() {
    this.login_userId = this.$store.getters.userId || window.localStorage.getItem('userId') // 拿到当前登录者的userId
  },
  methods: {
    // tab 接受点击
    handleClickTab(tab, event) {

    },
    // 获取菜单id 列表
    getMenuId(menu_data, flt_type = true) {
      const perms = [] // 存所具有的 权限的 menuId
      function getMenuPerms(menu) { // 获取的当前菜单所拥有的权限列表, 数组格式
        menu.forEach((item, i) => {
          if (flt_type && item.type != 1) { // 过滤掉type==1的
            perms.push(item.menuId)
          } else if (!flt_type) { // 不做过滤的所有的都 添加到perms中
            perms.push(item.menuId)
          }
          if (item.childrenList.length > 0) {
            getMenuPerms(item.childrenList)
          }
        })
      }
      getMenuPerms(menu_data)
      return perms
    },
    // 获取角色列表
    getListRole() {
      // 网络请求: 获取角色名和角色Id的 列表
      listRole(this.listQuery.page, this.listQuery.limit, this.listQuery.keyword).then(res => {
        this.total = parseInt(res.data.total) // 这个total 前端没做过滤,,后端已过滤,  只返回,当前登录者创建的角色
        this.list_role = []
        this.list_role = res.data.records.filter((val, i) => { // 过滤 得到当前登录者 所创建的角色列表
          return val.createUserId == this.login_userId
        })

        this.list_role.forEach((val, i) => {
          this.$set(val, 'menu_perm', this.login_menu) // 将当前登录者 所具有的权限,存到 角色名和角色id这个列表中

          permRole(val.roleId).then(res => {
            if (res.data && res.data.length > 0) {
              // console.log(val.roleId, res.data)
              this.$set(val, 'check_perm', this.getMenuId(res.data))
              // console.log(val.roleId, this.getMenuId(res.data, false))
            } else {
              this.$set(val, 'check_perm', [])
            }
          })
        })

        // 设置活动 tab页
        if (this.list_role.length > 0 && (this.active_name == '' || this.active_name == 0)) {
          this.active_name = this.list_role[0].roleId // 设置第一个 处于活跃
          // this.active_name = this.list_role[(this.listQuery.page-1)*this.listQuery.limit].roleId // 设置当页第一个 处于活跃
        }
      })
    },
    changePage() {
      this.active_name = ''
      this.getListRole()
    },

    // 点击了 '编辑' 或添加======================================================
    handleUpdate(row, str) {
      if (str == 'create') this.resetTemp() // 清空
      if (str == 'update') this.temp = Object.assign({}, row) // 克隆一个对象
      this.dialogStatus = str
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate() // 清空form
        // this.list_role.
        // this.$refs['tree_add'].setCurrentKey(this.list_role.roleId==this.)   // 清空tree
      })
    },
    // 编辑: 确认更新数据
    updateData(node, check) {
      let perms = [] // 存所具有的 权限的 menuId
      if (node.childrenList.length > 0) {
        perms = this.getMenuId(node.childrenList, false) // 得到子节点的menuId
      }
      perms.unshift(node.menuId) // 当前节点的menuId
      perms = perms.concat(check.halfCheckedKeys) // 父 节点的menuId
      console.log(perms)
      const is_check = (check.checkedKeys.indexOf(node.menuId) != -1) ? 1 : 0
      const permsId = perms.join(',')
      // js  utf8编码===========================
      function encodeUtf8(text) {
        const code = encodeURIComponent(text)
        const bytes = []
        for (var i = 0; i < code.length; i++) {
          const c = code.charAt(i)
          if (c === '%') {
            const hex = code.charAt(i + 1) + code.charAt(i + 2)
            const hexVal = parseInt(hex, 16)
            bytes.push(hexVal)
            i += 2
          } else bytes.push(c.charCodeAt(0))
        }
        return bytes
      }
      // js   utf8 解码================================
      function decodeUtf8(bytes) {
        var encoded = ''
        for (var i = 0; i < bytes.length; i++) {
          encoded += '%' + bytes[i].toString(16)
        }
        return decodeURIComponent(encoded)
      }
      // 网络请求
      if (this.active_name == 1) {
        this.$message({
          message: '超级管理员角色不能更改!',
          type: 'warning',
          duration: 5000,
          showClose: true,
          center: true
        })
        this.getListRole()
      } else {
        editRole(this.active_name, is_check, permsId).then(() => {
          this.getListRole()
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 4000
          })
        }).catch(err => {
          this.getListRole()
        })
      }
    },
    // 确认添加了一个角色
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const res_data1 = this.$refs['tree_add'].getCheckedKeys()
          const res_data2 = this.$refs['tree_add'].getHalfCheckedKeys()
          const perms = [...res_data1, ...res_data2]
          // console.log(perms)
          // res_data.forEach( (item,i) => {   // 获取所有被选中的 菜单id
          //   perms.push(item.menuId)
          // })
          this.temp.permIds = perms

          addRole(this.temp.permIds, this.temp.remark, this.temp.roleName).then(() => {
            // this.list.unshift(this.temp)
            this.getListRole()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 清空temp
    resetTemp() {
      this.temp = {
        temp: {
          roleId: '',
          roleName: '',
          remark: '',
          permIds: []
        }
      }
    },
    // 点击了删除===============================================
    handleDelete(row, index) {
      this.is_multip = false
      this.del_id = row.id
      this.del_index = index
      this.dialogPvVisible = true
    },
    // 点击了 批量删除
    handleDelmultip() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: '没有被选中项!',
          type: 'error',
          duration: 4000,
          showClose: true,
          center: true
        })
      } else {
        this.is_multip = true
        this.dialogPvVisible = true
      }
    },
    // 确认了删除
    delData() {
      let ids = []
      if (this.is_multip) { // 批量删
        this.multipleSelection.forEach((item, i) => {
          ids.push(item.id)
        })
      } else {
        ids = [this.del_id]
      }
      if (this.active_name == 1) {
        this.$message({
          message: '超级管理员角色不能删除!',
          type: 'warning',
          duration: 5000,
          showClose: true,
          center: true
        })
        this.getListRole()
      } else {
        delRole([this.active_name]).then(() => { // 暂时写死this.active_name
          this.dialogPvVisible = false
          // this.list.splice(this.del_index, 1)
          this.getListRole()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 4000
          })
        })
      }
    },

    // 搜索
    handleFilter() {
      this.active_name = ''
      this.listQuery.page = 1
      this.getListRole()
    },
    // 批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style lang="scss">
  $theme_text: #0F8BFD;
  $theme_bg: #0189FF;
  $backg:rgba(0,0,0,0);
  $deep_text: #5E5E5E;

  .tab-container .el-tabs__nav.is-top {
    // background-color: $theme_text;
    border: none !important;
  }
  .tab-container .el-tabs__nav-scroll {
    background-color: #F7F8FC;
    border: none !important;
  }
  .tab-container .el-tabs__item.is-top {
    margin-right: 20px;
    border: none !important;
    background-color: $theme_bg;
    color: #fff;
    border-radius: 10px 10px 0 0 !important;
  }
  .tab-container .el-tabs__item.is-top.is-active {
    background-color: #fff;
    color: $theme_bg;
  }
  .tab-container .el-tabs__item.is-top:hover {
    background-color: #fff;
    color: $theme_bg;
  }

  .tree-container {
    display: inline-block;
    padding: 20px 0;
    .el-tree {
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;
      .el-tree-node {
        margin-right: 30px;
      }
    }
  }

</style>

<style lang="scss" scoped>
  $theme_text: #0F8BFD;
  $backg:rgba(0,0,0,0);
  $deep_text: #5E5E5E;

  .app-container {
    // background-color: #f99 !important;
    .conduct {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 9;
      width:50%;
      display: flex;
      justify-content: space-between;
      .conduct-input {
        margin-right: 10px;
        border: 0;
        input {
          background: transparent;
          border: 0;
          -webkit-appearance: none;
          border-radius: 0px;
          padding: 12px 5px 12px 15px;
          color: $deep_text;
          // height: 47px;
          caret-color: $deep_text;

          &:-webkit-autofill {
            box-shadow: 0 0 0 1000px $backg inset !important;
            -webkit-text-fill-color: $deep_text !important;
          }
        }
        .el-button {
          color: #fff;
          background-color: #0F8CFD;
        }
      }
    }
    .el-tabs {
      background-color: #fff;
      .role-tilte {
        padding: 0 20px;
        display: flex;
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid #EAEBF0;
        .title-item {
          margin-right: 60px;
        }
      }
      .title-icon {
        display: inline-block;
        background-color: $theme_text;
        width: 4px;
        height: 20px;
        border-radius: 2px;
        transform: translateY(5px);
      }

      .role-tree {
        padding: 0 20px;
        .tree-title {
          display: inline-block;
          margin-right: 10px;
        }
      }
    }

    .el-dialog {
      .del-data {
        text-align: center;
        margin-bottom: 16px;
        img {
          width: 110px;
          height: 110px;
        }
      }
      .del-img {}
      // min-width: 490px !important;
      // .el-input {
      //   width: 100%;
      //   background-color: blueviolet;
      // }
    }
  }
</style>
